package com.kkd.kkdapp.activity;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.CustomScrollView;
import com.kkd.kkdapp.view.CustomScrollView.OnRefreshListener;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 天天赚
 * 
 * @author mty
 * 
 */
public class AccountEverydayActivity extends BaseActivity implements
		OnClickListener {

	private final int CODE_ZERO = 1; // code=0
	private final int CODE_ELSE = 2; // code=其它
	private final int CLOSE_PULLDOWN = 4; // 关闭下拉
	private RelativeLayout mReturn; // 后退
	private WebView mWebView;
	private String url;
	private RelativeLayout mCheck; // 查看明细
	private RelativeLayout mCheck_new; // 查看明细
	private CustomScrollView mScrollView; // 下拉刷新
	// private String version;
	private TextView yesterday; // 昨日收益
	private TextView buy_amount; // 购买总额
	private TextView accumulative; // 累计收益
	private TextView subscription; // 认购
	private String fa = "1000000"; // 剩余金额
	private double balance;
	private String yuebaoid; // 天天赚ID
	private TextView mRollout; // 转出
	private String myb;
	private String title; // 标题
	private boolean subscriptionflag;
	private long lowestAmount;
	private TextView check_tv;
	private int interest;
	private int yuEBaoSendTime = 0;
	private DecimalFormat df = new DecimalFormat("0.00");
	private DecimalFormat df1 = new DecimalFormat("###,##0.00");
	private double rates;
	private String yti;
	private String ti;
	private PopupWindow mDialog;
	private long sellFreeAmoutLine; // 今日总限额
	private long sellFreeAmout; // 剩余限额
	private double sellRates; // 进度
	private boolean REFRESHFLAG = true;
	private String timeLimitDesc;
	private long sellLimitAmount;
	private String title_xieYi;
	private String url_xieYi;
	private int status_canTender;
	private String desc_canTender;
	private boolean isCanTender = true;
	private ImageView rel_tip_img;
	public static Activity mActivity;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			String desc = "";
			switch (msg.what) {
			case CODE_ZERO:
				yesterday.setText(df1.format(Double.parseDouble(myb)));
				buy_amount.setText(yti);
				accumulative.setText(ti);
				LogUtil.e("url", url);
				if (REFRESHFLAG) {
					User user = CurUserModel.getCurUser();
					if (user != null) {
						String postdata = "customerId=" + user.customerId
								+ "&token=" + user.token + "&channel=Android";
						mWebView.postUrl(url, postdata.getBytes());
					} else {
						String postdata = "customerId=&token=&channel=Android";
						mWebView.postUrl(url, postdata.getBytes());
					}
					// mWebView.loadUrl(url);
					REFRESHFLAG = false;
				}
				break;
			case CODE_ELSE:
				desc = (String) msg.obj;
				showToast(desc);
				break;
			case CLOSE_PULLDOWN:
				mScrollView.onRefreshComplete();
				break;
			default:
				break;
			}
		};
	};
	private View rel_tip;
	private TextView hint_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_accoun_everyday);
		mActivity = this;
		initView();
		setLitener();
		logic();
	}

	public void initView() {
		rel_tip = this.findViewById(R.id.rel_tip);
		mReturn = (RelativeLayout) this.findViewById(R.id.add_title_img);
		mWebView = (WebView) this.findViewById(R.id.everyday_webview);
		mCheck = (RelativeLayout) this.findViewById(R.id.check);
		mCheck_new = (RelativeLayout) this.findViewById(R.id.check_new);
		mScrollView = (CustomScrollView) this.findViewById(R.id.scrollview);
		yesterday = (TextView) this.findViewById(R.id.yesterday);
		buy_amount = (TextView) this.findViewById(R.id.buy_amount);
		accumulative = (TextView) this.findViewById(R.id.accumulative);
		subscription = (TextView) this.findViewById(R.id.subscription);
		mRollout = (TextView) this.findViewById(R.id.rollout);
		check_tv = (TextView) this.findViewById(R.id.check_tv);
		rel_tip_img = (ImageView) this.findViewById(R.id.rel_tip_img);
		check_tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
		hint_tv = (TextView) findViewById(R.id.hint_tv);
	}

	public void setLitener() {
		rel_tip.setOnClickListener(this);
		mReturn.setOnClickListener(this);
		mCheck.setOnClickListener(this);
		mCheck_new.setOnClickListener(this);
		subscription.setOnClickListener(this);
		mRollout.setOnClickListener(this);
		mScrollView.setOnRefreshListener(new OnRefreshListener() {
			public void onRefresh() {

				// mWebView.reload(); // 刷新
				// mWebView.loadUrl(url);
				requestQueryYuebaoInfo();

			}
		});
	}

	public void logic() {
		WebSettings webSettings = mWebView.getSettings();
		// 设置WebView属性，能够执行Javascript脚本
		webSettings.setJavaScriptEnabled(true);
		// 设置可以访问文件
		webSettings.setAllowFileAccess(true);
		// 设置支持缩放
		webSettings.setBuiltInZoomControls(true);
		// 加载需要显示的网页
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				mWebView.loadUrl("file:///android_asset/rate.html");
			};

			@Override
			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				handler.proceed();
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.add_title_img: // 后退
			finish();
			break;
		case R.id.rel_tip:
			LogUtil.e("TAG", "-------------");
			LogUtil.e("rel_tip_imgX", "" + rel_tip_img.getX());
			LogUtil.e("rel_tip_imgY", "" + rel_tip_img.getY());
			LogUtil.e("width", "" + SystemUtils.getScreenWidth(this));
			LogUtil.e("height", "" + SystemUtils.getScreenHeight(this));
			showmDialog(rel_tip_img, "您的天天赚持有总额，可以随时转出", rel_tip_img.getX());
			break;
		case R.id.check: // 查看明细
			intent = new Intent(this, EverydayDealDetailsActivity.class);
			startActivity(intent);
			break;
		case R.id.check_new: // 查看明细
			intent = new Intent(this, EverydayDealDetailsActivity.class);
			startActivity(intent);
			break;
		case R.id.subscription: // 认购
			String fa1 = df1.format(Double.parseDouble(fa));
			SystemUtils.onEvent("Account_Current_TransferIN", 1);
			if (AppUtil.isConnect(this)) {
				if (subscriptionflag) {
					if (PreferenceUtils.getInstance().getAutonym(this) == 1) { // 身份认证
						if (PreferenceUtils.getInstance()
								.getBoundBankCard(this) == 1) { // 判定银行卡是否绑定
							intent = new Intent(this,
									CurrentTenderActivity.class);
							intent.putExtra("surplus", fa1);
							intent.putExtra("yuebaoid", yuebaoid);
							intent.putExtra("title", title);
							intent.putExtra("lowestAmount", lowestAmount);
							String interests = df.format(interest * 0.01);
							intent.putExtra("interests", interests);
							intent.putExtra("rates", rates);
							intent.putExtra("url_xieYi", url_xieYi);
							intent.putExtra("title_xieYi", title_xieYi);
							startActivity(intent);
						} else {
							if (balance == 0) {
								intent = new Intent(this,
										ForTenderActivity.class);
								intent.putExtra("enterTypeFlag", 4);
								intent.putExtra("surplus", fa1);
								intent.putExtra("yuebaoid", yuebaoid);
								intent.putExtra("title", title);
								intent.putExtra("lowestAmount", lowestAmount);
								String interests = df.format(interest * 0.01);
								intent.putExtra("interests", interests);
								intent.putExtra("rates", rates);
								intent.putExtra("url_xieYi", url_xieYi);
								intent.putExtra("title_xieYi", title_xieYi);
								startActivity(intent);
							} else {
								intent = new Intent(this,
										CurrentTenderActivity.class);
								intent.putExtra("surplus", fa1);
								intent.putExtra("title", title);
								intent.putExtra("yuebaoid", yuebaoid);
								intent.putExtra("lowestAmount", lowestAmount);
								String interests = df.format(interest * 0.01);
								intent.putExtra("interests", interests);
								intent.putExtra("rates", rates);
								intent.putExtra("url_xieYi", url_xieYi);
								intent.putExtra("title_xieYi", title_xieYi);
								startActivity(intent);
							}
						}
					} else {
						intent = new Intent(this, ForTenderActivity.class);
						intent.putExtra("enterTypeFlag", 4);
						intent.putExtra("surplus", fa1);
						intent.putExtra("yuebaoid", yuebaoid);
						intent.putExtra("title", title);
						intent.putExtra("lowestAmount", lowestAmount);
						String interests = df.format(interest * 0.01);
						intent.putExtra("interests", interests);
						intent.putExtra("rates", rates);
						intent.putExtra("url_xieYi", url_xieYi);
						intent.putExtra("title_xieYi", title_xieYi);
						startActivity(intent);
					}
				}
			} else {
				showToast(R.string.network_anomaly);
			}
			break;
		case R.id.rollout: // 转出
			SystemUtils.onEvent("Account_Current_TransferOut", 1);
			if (AppUtil.isConnect(this)) {
				intent = new Intent(this, Everyday_WithdrawActivity.class);
				intent.putExtra("myYuebaoBalance", myb);
				intent.putExtra("sellFreeAmoutLine", sellFreeAmoutLine);
				intent.putExtra("sellFreeAmout", sellFreeAmout);
				intent.putExtra("sellRates", sellRates);
				intent.putExtra("timeLimitDesc", timeLimitDesc);
				intent.putExtra("sellLimitAmount", sellLimitAmount);
				startActivity(intent);
			} else {
				showToast(R.string.network_anomaly);
			}
			break;
		}
	}

	/**
	 * 天天赚主页面
	 */
	public void requestQueryYuebaoInfo() {

		String cusetomerIdAndToken = PreferenceUtils.getInstance()
				.getcustomerId(this);
		String[] cat = cusetomerIdAndToken.split("&");
		if (cat == null || cat.length == 0)
			return;
		KkdHttpMagager.getInstance().getAccounEverydayManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {

							String responseString = responseBody.toString();
							LogUtil.e("responseString", responseString);

							JSONObject data = new JSONObject(responseString);

							lowestAmount = data.getLong("lowestAmount");

							int yesterdayIncome = data
									.getInt("yesterdayIncome");

							yti = df.format(yesterdayIncome * 0.01);

							int myYuebaoBalance = data
									.getInt("myYuebaoBalance");

							myb = df.format(myYuebaoBalance * 0.01);

							int totalIncome = data.getInt("totalIncome");

							ti = df.format(totalIncome * 0.01);

							int freeAmount = data.getInt("freeAmount");

							fa = df.format(freeAmount * 0.01);

							yuebaoid = data.getString("yuebaoId");

							title = data.getString("title");

							url = data.getString("url");

							interest = data.getInt("interest");

							rates = data.getDouble("rates");

							yuEBaoSendTime = data.getInt("yuEBaoSendTime");

							sellLimitAmount = data.getLong("sellLimitAmount");

							sellFreeAmoutLine = data
									.getLong("sellFreeAmoutLine");

							sellFreeAmout = data.getLong("sellFreeAmout");

							sellRates = data.getDouble("sellRates");
							timeLimitDesc = data.getString("timeLimitDesc");
							// 天天赚协议
							JSONObject jsonObject_yuebaoXy = data
									.getJSONObject("yuebaoXy");
							title_xieYi = jsonObject_yuebaoXy
									.getString("title");
							url_xieYi = jsonObject_yuebaoXy.getString("url");
							// 天天赚是否下架及其可投
							JSONObject jsonObject_canTender = data
									.getJSONObject("stopInfo");
							status_canTender = jsonObject_canTender
									.getInt("status");
							desc_canTender = jsonObject_canTender
									.getString("desc");
							// 展示天天赚下架信息
							if (TextUtils.isEmpty(desc_canTender)) {
								hint_tv.setVisibility(View.GONE);
							} else {
								hint_tv.setText(desc_canTender);
								hint_tv.setVisibility(View.VISIBLE);
							}
							// 天天赚是是否可投
							if (status_canTender == 0) {// 不可投
								isCanTender = false;
								subscription
										.setBackgroundResource(R.drawable.recharge_bt_bg_hui);
								subscription.setEnabled(false);
							} else {
								isCanTender = true;
								subscription
										.setBackgroundResource(R.drawable.recharge_bt_bg);
							}

							handler.sendEmptyMessage(CODE_ZERO);
							mTimerHandler.sendEmptyMessage(1003);
							handler.sendEmptyMessage(CLOSE_PULLDOWN);

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = CODE_ELSE;
						msg.obj = desc;
						handler.sendMessage(msg);
						handler.sendEmptyMessage(CLOSE_PULLDOWN);
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		getAccountInfo();
		requestQueryYuebaoInfo();
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		String customerIdAndToken = PreferenceUtils.getInstance()
				.getcustomerId(this);
		String[] cat = customerIdAndToken.split("&");
		if (cat.length < 2)
			return;
		KkdHttpMagager.getInstance().getAccountInfoManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							balance = data.getDouble("balance");
							LogUtil.e("", "" + balance);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = CODE_ELSE;
						msg.obj = desc;
						handler.sendMessage(msg);
					}
				});
	}

	public static final int PERIOD = 1000;
	public int maxTime = 0;
	public static final int RECORD_TIMER = 8112;
	public static final int RECORD_DONE = 8113;
	public static final int RECORD_ERROR = 8114;
	private Timer mTimer = new Timer();
	private TimerTask mTimerTask = null;
	private int mRecordTime = 0;
	private boolean isRecoding = false;
	public TimerHandler mTimerHandler = new TimerHandler(this);
	protected boolean onStarting = false;

	public static class TimerHandler extends Handler {
		WeakReference<AccountEverydayActivity> reference;

		public TimerHandler(AccountEverydayActivity view) {
			reference = new WeakReference<AccountEverydayActivity>(view);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				if (reference != null && reference.get() != null)
					reference.get().updatePurchaseBtn();
				break;
			case RECORD_DONE:
				if (reference != null && reference.get() != null)
					reference.get().onTimerFinish();
				break;
			case 1003:
				if (reference != null && reference.get() != null) {
					reference.get().updateUI();
				}
				break;
			default:
				break;
			}
		}
	}

	public void startTime() {
		mRecordTime = 0;
		if (mTimerTask == null) {
			mTimerTask = new RecordTimeTask();
			mTimer.schedule(mTimerTask, 0, PERIOD);
		}
		isRecoding = true;

	}

	public void updateUI() {
		if (Double.parseDouble(fa) == 0) {
			subscriptionflag = false;
			subscription.setText("转入结束");
		} else {
			subscriptionflag = true;
			subscription.setText("转入");
		}
		if (isCanTender) {
			if (yuEBaoSendTime > 0) {
				subscription.setAlpha(0.5f);
				maxTime = yuEBaoSendTime;
				subscription.setEnabled(false);
				updatePurchaseBtn();
				startTime();
			} else {
				subscription.setText("转入");
				subscription.setAlpha(1.0f);
				subscription.setEnabled(true);
			}
		}

	}

	public void onTimerFinish() {
		requestQueryYuebaoInfo();

	}

	public void updatePurchaseBtn() {
		int dtime = maxTime - mRecordTime;
		// Date time = new Date();
		// time.setTime(dtime*1000);
		// SimpleDateFormat df = new SimpleDateFormat("hh 时 mm 分 ss 秒");
		// String strTime = df.format(time);
		int ss = dtime % 60;
		int mm = (dtime / 60) % 60;
		int hh = dtime / 60 / 60;
		String strTime = String.format("%02d 时 %02d 分 %02d 秒", hh, mm, ss);
		subscription.setText(strTime);

	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				mRecordTime++;
				if (mRecordTime <= maxTime) {
					Message message = new Message();
					message.what = RECORD_TIMER;
					message.obj = mRecordTime;
					mTimerHandler.sendMessage(message);
				} else {
					Message message = new Message();
					message.what = RECORD_DONE;
					message.arg1 = mRecordTime;
					message.obj = "";
					mTimerHandler.sendMessage(message);
					isRecoding = false;
				}
			}

		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}

	public void showmDialog(ImageView img, String describe, float coordinate) {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}

		mDialog = DialogUtils.bubblePupopwindow4(AccountEverydayActivity.this,
				describe, coordinate);
		mDialog.showAsDropDown(img);
	}
}
